
<template>
  <div class="header_information page-container">
    <!-- 头部 -->
    <el-row class="header_name">
      <el-col
        :span="24"
        class="header_text"
      >
        <h1>组委会管理</h1>
      </el-col>
      <el-col :span="24">
        <div class="header_line"></div>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row class="el_row_btn">
      <el-col
        :span="24"
        class="content"
      >
        <div class="content_top_btn">
          <div>
            <el-button
              size="large"
              :icon="Plus"
              @click="handleShare"
              type="primary"
            >添加组委会</el-button>
          </div>
          <div>
            <el-input
              class="top_search_inp"
              v-model="query_data.name"
              placeholder="请输入组委会名称"
              clearable
            />
            <el-button
              size="large"
              :icon="Search"
              circle
              :loading="loading"
              @click="() => {
              handleLoad(true)
            }"
            />
          </div>

        </div>
      </el-col>
    </el-row>
    <!-- 内容 -->
    <el-row>
      <el-col :span="24">
        <el-table
          empty-text="暂无数据..."
          :data="data"
          border
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >

          <el-table-column
            label="机构 ID"
            prop="userId"
            width="100"
          />

          <el-table-column
            label="组委会名称"
            prop="name"
          />
          <el-table-column
            label="组委会地址"
            prop="address"
          />
          <el-table-column
            label="负责人姓名"
            prop="headName"
          />

          <el-table-column
            label="负责人电话"
            prop="headPhone"
          />
          <el-table-column
            label="目标数"
            prop="targetNumber"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            width="180"
          />
          <el-table-column
            label="操作"
            prop="Address"
            width="100"
          >
            <template v-slot="{ row }">
              <el-dropdown trigger="click">
                <span class="el_dropdown_link">
                  操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleredact(row)"> 编辑 </el-dropdown-item>
                    <el-dropdown-item @click="handleDel(row)"> 删除 </el-dropdown-item>
                    <el-dropdown-item @click="handleResetPasswords(row)"> 重置密码 </el-dropdown-item>
                    <el-dropdown-item @click="handleSetTargetNumber(row)"> 设置目标人数 </el-dropdown-item>
                    <el-dropdown-item @click="handleIdCode(row)"> ID码获取 </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 弹窗 -- 添加组委会 -->
    <el-dialog
      v-model="centerShareDialogVisible"
      width="50%"
      title="添加组委会"
    >
      <el-form
        :label-width="formLabelWidth"
        size="large"
        :model="reg_data"
        ref="reg_data_ref"
        :rules="reg_data_rules"
      >
        <div class="block-container">
          <div class="form-container">
            <el-form-item
              label="组委会名称"
              prop="name"
            >
              <el-input
                v-model="reg_data.name"
                placeholder="请输入组委会名称"
              />
            </el-form-item>
            <el-form-item
              label="地址"
              prop="address"
            >
              <el-input
                v-model="reg_data.address"
                placeholder="请输入地址"
              />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="phone"
            >
              <el-input
                v-model="reg_data.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
            >
              <el-input
                v-model="reg_data.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
            <!-- <el-form-item
              label="证件执照"
              prop="licenseImg"
            >
              <div class="Form_upload">
                <UploadImage v-model="reg_data.licenseImg" />
                <el-text
                  type="info"
                  size="small"
                  style="line-height:22px"
                >上传单位相关证件执照（如营业执照、办学许可证）只能上传 JPG/PNG 文件，且不超过 5 MB</el-text>
              </div>

            </el-form-item> -->
            <el-form-item
              label="负责人姓名"
              prop="headName"
            >
              <el-input
                v-model="reg_data.headName"
                placeholder="请输入负责人姓名"
              />
            </el-form-item>
            <el-form-item
              label="负责人联系方式"
              prop="headPhone"
            >
              <el-input
                v-model="reg_data.headPhone"
                placeholder="负责人联系方式"
              />
            </el-form-item>

            <el-form-item
              label="负责人邮箱"
              prop="headEmail"
            >
              <el-input
                v-model="reg_data.headEmail"
                placeholder="负责人邮箱"
              />
            </el-form-item>
            <el-form-item
              label="所选地区"
              prop="county"
            >
              <ProvinceSelect
                :isW="true"
                v-model:economize="reg_data.economize"
                v-model:market="reg_data.market"
                v-model:county="reg_data.county"
                :showCounty="true"
              />

            </el-form-item>
            <el-form-item>
              <el-button @click="centerShareDialogVisible = false, reg_data.value = {}">取消</el-button>
              <el-button
                type="primary"
                :loading="reg_loading"
                @click="handleReg"
              >保存</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <!-- 弹窗———— 编辑 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="编辑组委会"
      width="50%"
      align-center
    >

      <el-form
        :label-width="formLabelWidth"
        size="large"
        :model="reg_data"
        ref="reg_data_ref"
        :rules="reg_data_rules"
      >
        <div class="block-container">

          <div class="form-container">

            <el-form-item
              label="组委会名称"
              prop="name"
            >
              <el-input
                v-model.trim="reg_data.name"
                placeholder="请输入组委会名称"
              />
            </el-form-item>
            <el-form-item
              label="地址"
              prop="address"
            >
              <el-input
                v-model.trim="reg_data.address"
                placeholder="请输入地址"
              />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input
                v-model.trim="reg_data.phone"
                placeholder="请输入手机号"
                disabled
              />
            </el-form-item>

            <el-form-item
              label="负责人姓名"
              prop="headName"
            >
              <el-input
                v-model.trim="reg_data.headName"
                placeholder="请输入负责人姓名"
              />
            </el-form-item>
            <el-form-item
              label="负责人联系方式"
              prop="headPhone"
            >
              <el-input
                v-model.trim="reg_data.headPhone"
                placeholder="负责人联系方式"
              />
            </el-form-item>

            <el-form-item
              label="负责人邮箱"
              prop="headEmail"
            >
              <el-input
                v-model.trim="reg_data.headEmail"
                placeholder="负责人邮箱"
              />
            </el-form-item>
            <el-form-item
              label="所选地区"
              prop="county"
            >
              <ProvinceSelect
                :isW="true"
                v-model:economize="reg_data.economize"
                v-model:market="reg_data.market"
                v-model:county="reg_data.county"
                :showCounty="true"
              />

            </el-form-item>
            <el-form-item>
              <el-button @click="centerDialogVisible = false">取消</el-button>
              <el-button
                type="primary"
                :loading="reg_loading"
                @click="handleEnter"
              >保存</el-button>
            </el-form-item>
          </div>
        </div>

      </el-form>

    </el-dialog>
    <!-- 弹窗--设置目标人数 -->
    <el-dialog
      v-model="NumberDialogVisible"
      title="设置目标人数"
      width="40%"
      align-center
    >
      <el-form
        label-width="95px"
        size="large"
      >

        <div class="form-container">
          <el-form-item
            label="目标人数"
            prop="name"
          >
            <el-input
              v-model="targetNumber"
              placeholder="设置目标人数"
            />
          </el-form-item>

          <el-form-item>
            <el-button @click="NumberDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              :loading="reg_loading"
              @click="handleEnterNumber"
            >保存</el-button>
          </el-form-item>
        </div>
      </el-form>

    </el-dialog>
    <!-- 弹窗--ID码上传 -->
    <el-dialog
      v-model="IdCodeDialogVisible"
      title="ID码上传"
      width="40%"
      align-center
    >
      <el-form
        label-width="95px"
        size="large"
      >

        <div class="form-container">
          <el-form-item
            label="ID码上传"
            prop="idImage"
          >
            <UploadImage v-model="idImage" />
          </el-form-item>

          <el-form-item>
            <el-button @click="IdCodeDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              :loading="reg_loading"
              @click="handleVisibleIdCode"
            >保存</el-button>
          </el-form-item>
        </div>
      </el-form>

    </el-dialog>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        @current-change="handlePage"
      />
    </div>
  </div>
</template>

<script  setup>
import ProvinceSelect from "@/components/province-select/index.vue"
import UploadImage from "@/components/upload-image/index.vue"
import { onMounted } from "vue";
import { useValidateImage } from "@/hooks/useValidateImage"
import { usePage } from "@/hooks/usePage"
const { validate_image_url, update_validate_image } = useValidateImage();
import {
  Plus,
  WarningFilled,
  Search,
} from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus';
// 接口
import { getOrganizers, updateAgent, resetPassword, deleteAgentOrOrganizer, enterAgent, setAgentTarget } from "@/api/manage/organcommitmenu/index.js";
import { updateIdImage } from '@/api/manage/agentmenu/index.js'
import { ref, markRaw } from "vue";

const {
  total,
  data,
  loading,
  query_data,
  handleLoad,
  handlePage
} = usePage({
  api_fn: getOrganizers,
  q_data: {
    name: ""
  }
})
// 重置密码
const handleResetPasswords = (row) => {
  const messageText = `您确认重置 ${row.name} (ID : ${row.userId
    }) 的密码?\n密码将重置为 <span style="color: red;">123456</span>`; ElMessageBox.confirm(
      messageText, '密码重置',
      {
        dangerouslyUseHTMLString: true, // 允许使用HTML
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled),
      }
    )
      .then(async () => {

        let res = await resetPassword(row.userId)
        if (res.success) {
          ElMessage({
            message: res.message,
            type: 'success',
          })
        }
      })
      .catch(() => {
        // 用户点击了取消按钮或者关闭了对话框
      });
}


// 全选
const multipleSelection = ref([])
const userIds = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  userIds.value = multipleSelection.value.map((item) => item.userId).join(',');

}

/**
 * 删除组委会
 */
const handleDel = (row) => {
  ElMessageBox.confirm("是否确定删除当前组委会？", "删除组委会", { type: "error" }).then(async () => {
    if (row.userId) {
      let res = await deleteAgentOrOrganizer(row.userId)

      if (res.success) {
        ElNotification({
          title: '成功',
          message: `删除${res.message}`,
          type: 'success',
        })
      } else {
        ElMessage.error(res.message)
      }
    } else if (userIds.value) {
      let res = await deleteAgentOrOrganizer(userIds.value)

      if (res.success) {
        ElNotification({
          title: '成功',
          message: `删除${res.message}`,
          type: 'success',
        })
      } else {
        ElMessage.error(res.message)
      }
    }
    handleLoad(true);

  })
}

// 设置目标人数
const unit = ref({})
const targetNumber = ref(null)
const NumberDialogVisible = ref(false)
const handleSetTargetNumber = (row) => {
  if (row.targetNumber) {
    targetNumber.value = row.targetNumber
  } else {
    targetNumber.value = ''
  }
  unit.value = {
    userId: row.userId,
    targetNumber
  }
  NumberDialogVisible.value = true
}
// 确定目标人数
const handleEnterNumber = async () => {
  let res = await setAgentTarget(unit.value)
  if (res.success) {

    ElMessage({
      message: res.message,
      type: 'success',
    })
    handleLoad(true);
    NumberDialogVisible.value = false
  } else {
    ElMessage.error(res.message)
  }
}


// 添加组委会
const centerShareDialogVisible = ref(false)
// 添加组委会按钮
const handleShare = () => {
  reg_data.value = {
    "name": "",   //名称
    "address": "",  //地址
    "phone": "", // 账号
    "password": "",  //密码
    // "licenseImg": '', //证件执照
    "licenseType": null,   //执照类型
    "licenseNumber": null,   //执照号码
    "headName": "",   //负责人姓名
    "headPhone": "",  //负责人联系方式
    "headEmail": "",  //负责人邮箱
    "economize": "",   //省id
    "market": "",   //市id
    "county": "",   //县id
    "userId": '',   //县id
  }
  centerShareDialogVisible.value = true
}

/**
 * 数据
 */
const reg_data = ref({
  "name": "",   //名称
  "address": "",  //地址
  "phone": "", // 账号
  "password": "",  //密码
  // "licenseImg": '', //证件执照
  "licenseType": null,   //执照类型
  "licenseNumber": null,   //执照号码
  "headName": "",   //负责人姓名
  "headPhone": "",  //负责人联系方式
  "headEmail": "",  //负责人邮箱
  "economize": null,   //省id
  "market": null,   //市id
  "county": null,   //县id
  "userId": '',   //县id
});
const reg_data_ref = ref();
const checkPhone = (rule, value, callback) => {
  const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/
  if (!value) {
    callback(new Error('手机号码不能为空'))
  }
  if (phoneReg.test(value)) {
    callback()
  } else {
    callback(new Error('手机号码格式错误'))
  }
}
const checkEmail = (rule, value, callback) => {
  const emailReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (!value) {
    callback(new Error('邮箱不能为空'))
  }
  if (emailReg.test(value)) {
    callback()
  } else {
    callback(new Error('邮箱格式错误'))
  }
}
const reg_data_rules = ref({
  name: [
    {
      type: 'string',
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    }
  ],
  address: [
    {
      type: 'string',
      required: true,
      message: '请输入地址',
      trigger: 'blur',
    }
  ],
  phone: [
    {
      required: true,
      validator: checkPhone,
      trigger: 'blur'
    }
  ],
  password: [
    {
      type: 'string',
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    }
  ],
  // licenseImg: [
  //   {
  //     type: 'string',
  //     required: true,
  //     message: '请上传证件执照',
  //     trigger: 'blur',
  //   }
  // ],
  headName: [
    {
      type: 'string',
      required: true,
      message: '请输入负责人姓名',
      trigger: 'blur',
    }
  ],
  headPhone: [
    {
      required: true,
      validator: checkPhone,
      trigger: 'blur'
    }
  ],
  headEmail: [
    {
      required: true,
      validator: checkEmail,
      trigger: 'blur'
    }
  ],
  county: [
    {
      required: true,
      message: '请选择地区',
    }
  ],
});
const reg_loading = ref(false)
const handleReg = async () => {

  reg_data_ref.value.validate(async (v, rule) => {

    if (!v) {
      return;
    }
    reg_loading.value = true;
    let res = await enterAgent(reg_data.value)
    if (!res.success) {
      ElMessage.error(res.message)
    } else {
      ElMessage.success(res.message)
      centerShareDialogVisible.value = false
      handleLoad(true);
    }
    reg_loading.value = false;
  })
};

// 弹窗--编辑 数据回显
const formLabelWidth = '130px'
const centerDialogVisible = ref(false)
//  const form = ref({ })

const handleredact = (row) => {
  let find = data.value.find((item) => item.userId == row.userId);
  if (find) {
    // const { ...find } = reg_data.value
    reg_data.value = { ...find };
  }
  centerDialogVisible.value = true
}
// 弹窗--编辑 确定
const handleEnter = async () => {
  reg_data_ref.value.validate(async (v, rule) => {
    if (!v) {
      return;
    }
    centerDialogVisible.value = false
    let res = await updateAgent(reg_data.value)

    if (res.success) {
      ElMessage({
        message: res.message,
        type: 'success',
      })
      handleLoad(true);
    } else {
      ElMessage.error(res.message)
    }

  })
}

// id码获取
const IdCodeDialogVisible = ref(false)
const IdCodeuserId = ref('')
const handleIdCode = (row) => {
  console.log(row.idImage);
  IdCodeDialogVisible.value = true
  IdCodeuserId.value = row.userId
  if (row.idImage != null) {
    idImage.value = row.idImage
  } else {
    idImage.value = ''
  }

}

const idImage = ref('')
// 确定id码获取
const handleVisibleIdCode = async () => {
  if (!idImage.value) {
    ElMessage.error('ID码不能为空');
    return;
  }
  IdCodeDialogVisible.value = false
  let res = await updateIdImage({ userId: IdCodeuserId.value, idImage: idImage.value })
  if (res.success) {
    ElMessage({
      message: res.message,
      type: 'success',
    })
    handleLoad(true);
  } else {
    ElMessage.error(res.message)
  }
}
onMounted(() => {
  handleLoad(true);
});
</script>

<style lang="scss" scoped>
.header_information {
  padding: 20px;

  .header_name {
    margin-left: 10px;
    margin-right: 10px;

    .header_text {
      margin-left: -10px;
      margin-right: -10px;
    }

    h1 {
      font-size: 28px;
    }

    // 线
    .header_line {
      display: block;
      height: 1px;
      width: 100%;
      margin: 24px 0 20px 0;
      background-color: #8473f717;
    }
  }

  //   内容
  :deep(.table_btn_success) {
    padding: 0 5px !important;
    border: none;
  }

  .Form_upload {
    display: flex;
    flex-direction: column;
  }

  :deep(.el-table) .cell {
    padding: 0 10px;
  }

  .el_row_btn {
    margin-bottom: 20px;

    .content {
      .content_top_btn {
        display: flex;
        justify-content: space-between;

        .top_search_inp {
          width: 300px;
          height: 40px;
          margin-right: 5px;
        }

        .top_search_btn {
          width: 110px;
          margin-right: 5px;
        }
      }
    }
  }

  .el_dropdown_link {
    font-size: 14px;
  }

  :deep(.el-table)__cell {
    padding: 12px 0 !important;
  }

  .dialog_text {
    display: block;
    margin-top: 20px;
  }

  // 分页
  .pagination {
    margin-top: 30px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50px;
  }
}

// 头部主体
.header_content {
  width: 100%;
  height: 100px;
  font-size: 18px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  background: #312366;
  color: #333;
  line-height: 60px;

  .container {
    width: 1200px;
    margin: 0 auto;

    .container_left {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 1180px;
      min-height: 1px;
      margin-right: 10px;
      margin-left: 10px;

      .left_img {
        height: 50px;

        img {
          height: 100%;
        }
      }
    }
  }
}

// 内容主体
.content {
  .content_bgc {
    width: 100%;
    height: 100%;
    //   background-image: -webkit-linear-gradient(0deg, #5d5df9 0, #312366 100%);
    background-repeat: no-repeat;
    background-size: 100%;
    //   margin-bottom: 350px;

    .content_reg {
      display: flex;
      flex-direction: column;
      width: 740px;
      border-radius: 16px;
      background: #fff;
      margin: 0 auto;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
      padding: 20px;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      margin-top: 100px;

      .header {
      }

      .block-container {
        margin-top: 32px;

        .form-container {
          width: 512px;
          padding-top: 16px;
        }
      }
    }
  }
}

:deep(.el-input-group__append) {
  padding: 0;
  cursor: pointer;
  box-sizing: border-box;
}

.code-image {
  height: 100% !important;
  cursor: pointer;
  text-align: center;
}
</style>
